<template>
  <div id="box">
    <div class="otherDisposal">
      <div class="disposal">
        <!-- <div v-show="treatmentList.length === 0 && medicineList.length === 0">
          <center><h3>无数据</h3></center>
        </div> -->
        <div class="addContent">
          <el-button type="primary" style="
              float: right;
              margin-right: 40px;
              margin-top: 8px;
              padding: 8px 15px;
            " @click="popup">新增药物</el-button>
          <el-button type="primary" style="
              float: right;
              margin-right: 40px;
              margin-top: 8px;
              padding: 8px 15px;
            " @click="popupLife">新增生命支持</el-button>
        </div>
        <div v-show="treatmentList.length" class="lifeSupport">
          <div class="text-life">生命支持</div>
          <div v-for="(item, index) in treatmentList" :key="index" class="life-box">
            <span class="line" />
            <div class="life-lift">
              <el-checkbox-group v-model="item.treatment" class="life-many">
                <el-checkbox label="吸氧" />
                <el-checkbox label="心电监护" />
                <el-checkbox label="心肺复苏" />
                <el-checkbox label="气管插管" />
                <el-checkbox label="开通静脉通路" />
              </el-checkbox-group>
            </div>
            <div class="life-right">
              <span class="jizhen-text">
                <el-date-picker v-model="item.time" type="datetime" size="mini" value-format="yyyy-MM-dd HH:mm:ss"
                  placeholder="选择日期时间" />
              </span>
              <span class="jizhen-text">{{ item.department }}</span>
              <span>{{ item.doctor }}</span>
            </div>
            <div class="life-bottom">
              <div class="beizhutext">备注：</div>
              <el-input v-model="item.notes" placeholder="" style="width: 80%" @change="handleLifeText">{{ item.notes
                }}</el-input>
              <el-button type="primary" size="small" style="position: absolute;right: 70px; width: 60px;"
                @click="deleteData(item, 2)">删 除</el-button>
              <el-button type="primary" size="small" style="position: absolute;right: 0px; width: 60px;"
                @click="lifeTreatments(index)">保 存</el-button>
            </div>
          </div>
        </div>
        <div v-show="medicineList.length" class="drug">
          <div class="text-life">药物</div>
          <div v-for="(medicieneItem, target) in medicineList" :key="target" class="life-box">
            <el-button type="primary" size="small" style="position: absolute; right: 100px; bottom: 0px; width: 80px"
              @click="deleteData(medicieneItem, 1)">删 除</el-button>
            <el-button type="primary" size="small" style="position: absolute; right: 10px; bottom: 0px; width: 80px"
              @click="saveMedicine(target)">保 存</el-button>
            <span class="line" />
            <div class="life-lift">
              <div class="box-card" shadow="hover" style="margin-top: 10px">
                <el-form label-position="right" label-width="100px">
                  <div style="
                      border: #e4e4e4 solid 1px;
                      padding: 10px 10px 10px 0;
                      min-height: 100px;
                    ">
                    <div v-for="(item, index) in medicieneItem.orderDetailArr" :key="index">
                      <el-row :gutter="24" style="padding: 5px 0px 5px 30px; line-height: 40px">
                        <el-col :span="3">{{ item.itemName }}</el-col>
                        <el-col :span="3">{{ item.medicineName }}</el-col>
                        <el-col :span="4">
                          
                          <el-input v-model.trim="item.dosage" placeholder="剂量" />
                        </el-col>
                        <el-col :span="4">
                          <el-select v-model="item.unit" placeholder="请选择">
                            <el-option v-for="(el, el_index) in func(item.medicineUnit)" :key="el_index" :value="el" />
                          </el-select>
                          <!-- <el-input v-model="item.unit" placeholder="" /> -->
                        </el-col>
                        <el-col :span="3">
                          <el-date-picker v-model="item.medicineTime" type="datetime" format="yyyy-MM-dd HH:mm:ss"
                            value-format="timestamp" placeholder="选择日期时间" />
                        </el-col>
                        <!-- <el-col
                          v-if="
                            ['阿司匹林', '氯吡格雷', '替格瑞洛'].includes(
                              item.medicineName
                            )
                          "
                          :span="6"
                        >
                          <el-date-picker
                            v-if="medicieneItem.time == drugHistoryTime[item.medicineName].creatTime"
                            v-model="item.medicineTime"
                            type="datetime"
                            value-format="yyyy-MM-dd HH:mm:ss"
                            placeholder="选择日期时间"
                          />
                          <el-date-picker
                            v-else
                            v-model="drugHistoryTime[item.medicineName].meTime"
                            readonly
                            type="datetime"
                            value-format="yyyy-MM-dd HH:mm:ss"
                            placeholder="选择日期时间"
                            @focus="
                              historyTips(
                                drugHistoryTime[item.medicineName].creatTime
                              )
                            "
                          />
                        </el-col>
                        <el-col v-if="item.itemName == '抗凝药'" :span="6">
                          <el-date-picker
                            v-if="medicieneItem.time == drugHistoryTime[item.itemName].creatTime"
                            v-model="item.medicineTime"
                            type="datetime"
                            value-format="yyyy-MM-dd HH:mm:ss"
                            placeholder="选择日期时间"
                            @change="
                              anticoagulatingSync(item.medicineTime, target)
                            "
                          />
                          <el-date-picker
                            v-else
                            v-model="drugHistoryTime[item.itemName].meTime"
                            readonly
                            type="datetime"
                            value-format="yyyy-MM-dd HH:mm:ss"
                            placeholder="选择日期时间"
                            @focus="
                              historyTips(
                                drugHistoryTime[item.itemName].creatTime
                              )
                            "
                          />
                        </el-col>-->
                      </el-row>
                    </div>
                  </div>
                </el-form>
              </div>
              <el-dialog width="60%" title="选择药物" :visible.sync="innerVisible" append-to-body
                style="text-align: center">
                <el-checkbox-group v-model="modelData.checkList">
                  <el-checkbox v-for="(items, $index) in modelData.drugTemplate" :key="$index" :label="items" border
                    style="margin-bottom: 10px" @change="addDelList(items, $index)" />
                </el-checkbox-group>
                <span slot="footer" class="dialog-footer">
                  <el-button type="success" @click="innerVisible = false">确 定</el-button>
                </span>
              </el-dialog>
            </div>
            <div class="life-right">
              <span class="jizhen-text">
                {{ medicieneItem.time }}
                <!-- <el-date-picker
                  v-model="medicieneItem.time"
                  type="datetime"
                  size="mini"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  placeholder="选择日期时间"
                /> -->
              </span>
              <span class="jizhen-text">{{ medicieneItem.department }}</span>
              <span>{{ medicieneItem.doctor }}</span>
            </div>
            <div class="life-bottom">
              <div class="beizhutext">备注：</div>
              <el-input v-model="medicieneItem.chipsOrder.notes" placeholder="" style="width: 80%"
                @change="handleDrugText">
                {{ medicieneItem.chipsOrder.notes }}
              </el-input>
            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- 新增药物 -->
    <el-dialog title="新增药物" :visible.sync="rapidDispensingChange" class="dialogStyle" width="750px" top="18vh"
      :close-on-click-modal="false">
      <div style="display: flex; justify-content: space-around; flex-wrap: wrap">
        <el-button v-for="(item, index) in drugType" :key="index" type="primary" round
          style="width: 200px; margin: 5px 0px" @click="
            addInnerVisible = true;
          addNoRepetitionDrug(item);
          addModelData.tempName = index;
          ">{{ index }}</el-button>
      </div>
      <div class="box-card" shadow="hover" style="margin-top: 15px">
        <el-form label-position="right" label-width="100px">
          <div style="
              border: #eee solid 1px;
              padding: 10px 15px 10px 5px;
              min-height: 100px;
            ">
            <div v-for="(item, index) in saveList" :key="index">
              <el-row :gutter="20" style="padding: 10px; line-height: 40px">
                <el-col :span="1">{{ index + 1 }}</el-col>
                <el-col :span="4"> {{ item.itemName }}</el-col>
                <el-col :span="8"> {{ item.medicineName }}</el-col>
                <el-col :span="4">
                  <el-input v-model.trim="item.dosage" placeholder="剂量" />
                </el-col>
                <el-col :span="4">
                  <!-- <el-input v-model="item.unit" placeholder="请输入单位"></el-input> -->
                  <el-select v-model="item.unit" placeholder="请选择">
                    <el-option v-for="(el, el_index) in func(item.medicineUnit)" :key="el_index" :value="el" />
                  </el-select>
                </el-col>
                <el-col :span="2">
                  <el-button type="danger" plain @click="delDrugIndex(index, item.medicineName)">删除
                  </el-button>
                </el-col>
              </el-row>
            </div>
          </div>
          <div style="margin-top: 20px">
            <span style="font-size: 16px">备注 : </span>
            <el-input v-model="remarks" placeholder="请输入内容" style="width: 92%" clearable />
          </div>
        </el-form>
      </div>
      <el-dialog width="60%" title="选择药物" :visible.sync="addInnerVisible" append-to-body style="text-align: center">
        <el-checkbox-group v-model="addModelData.checkList">
          <el-checkbox v-for="(items, $index) in addModelData.drugTemplate" :key="$index" :label="items" border
            style="margin-bottom: 10px" @change="addDeleteList(items, $index, addModelData.tempName)" />
        </el-checkbox-group>
        <span slot="footer" class="dialog-footer">
          <el-button type="primary" @click="addInnerVisible = false">确 定</el-button>
        </span>
      </el-dialog>
      <span slot="footer" class="dialog-footer">
        <el-button @click="rapidDispensingChange = false">取 消</el-button>
        <el-button type="primary" @click="saveData()">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 新增生命支持 -->
    <el-dialog title="新增生命支持" :visible.sync="lifeChange" class="dialogStyle" width="60%" top="15px"
      :close-on-click-modal="false">
      <div class="box-card" shadow="hover" style="margin-top: 15px">
        <el-form label-position="right" label-width="100px">
          <div style="
              border: #eee solid 1px;
              padding: 30px 15px 10px 0;
              min-height: 100px;
            ">
            <el-checkbox-group v-model="lifeTreatment" class="life-many">
              <el-checkbox label="吸氧" />
              <el-checkbox label="心电监护" />
              <el-checkbox label="心肺复苏" />
              <el-checkbox label="气管插管" />
              <el-checkbox label="开通静脉通路" />
            </el-checkbox-group>
          </div>
          <el-row :gutter="24" style="margin-top: 20px">
            <el-col :span="24">
              <span style="
                  font-size: 16px;
                  display: inline-block;
                  margin-right: 30px;
                ">备 注 :</span>
              <el-input v-model="lifeRemarks" placeholder="请输入内容" style="width: 90%; display: inline-block" clearable />
            </el-col>
          </el-row>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="lifeClearAll(), lifeChange = false">取 消</el-button>
        <el-button type="primary" @click="addSaveLife()">保 存</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  queryListDisGet,
  saveOtherTreatments,
  saveOtherMedicineg,
  saveMedicine2,
  deleteOtherTreatments,
  selectList
} from '@/api/green-channel/otherDisposal'
import format from '@/utils/format'
import qs from 'qs'
export default {
  name: 'OtherDisposal',
  props: ['checkrowdata'], // 由主页面(父组件) 接收来的, 选择项的数据
  data() {
    return {
      /* 药品信息 */
      drugList: [],
      drugType: [], // 药品类型
      /* 新增生命支持 ------ */
      lifeChange: false,
      lifeTreatment: [],
      lifeRemarks: '',
      /* end -------------- */
      /* 新增药物 --------------------------- */
      rapidDispensingChange: false,
      addInnerVisible: false,
      saveList: [], // 弹出页面下方
      addModelData: {
        // dialog数据
        id: '',
        tempName: '',
        checkList: [], // 小弹出选中的多选-存值
        drugTemplate: [] // 小弹出可选的多选值
      },
      remarks: '',
      /* end ---------------------------- */
      dispatchIdInFo: {
        dispatchId: ''
      },
      Subscript: '',
      supportLift: [], // 生命复选值
      isSelected: true,
      treatmentList: [], // 生命支持列表
      lifeText: '', // 生命支持备注
      saveLifeData: {
        medicalid: this.checkrowdata.medicalId,
        dispatchId: this.checkrowdata.dispatchId,
        userId: this.checkrowdata.userId,
        treatment: [],
        user: '',
        department: this.checkrowdata.departmentName,
        notes: '',
        id: ''
      }, // 生命支持参数
      drugText: '', // 药物备注
      medicineList: [], // 药物列表
      saveMedicineData: {
        userId: '',
        missionId: '',
        medicalId: '',
        instanceType: '',
        json: {},
        status: 1,
        notes: '',
        polarity: '',
        version: '',
        judgement: '',
        hasAudio: false,
        hasPhoto: false,
        module: '',
        doctor: '',
        department: ''
      }, // 药物参数
      medicineType: '胸痛',
      innerVisible: false,
      modelData: {
        // dialog数据
        id: '',
        tempName: '',
        checkList: [], // 小弹出选中的多选-存值
        drugTemplate: [] // 小弹出可选的多选值
      },
      chestPain: {
        /* 抗血小板药*/
        dapt: ['阿司匹林', '替格瑞洛', '氯吡格雷', '普拉格雷', '西洛他唑'],
        /* ACEI/ARB*/
        aceiorarb: [
          '贝那普利',
          '依那普利',
          '赖诺普利',
          '卡托普利',
          '福辛普利',
          '摩西普利',
          '培哚普利',
          '雷米普利',
          '缬沙坦',
          '氯沙坦',
          '厄贝沙坦',
          '坎地沙坦',
          '替米沙坦',
          '奥美沙坦',
          '单片复方制剂',
          '沙库巴曲缬沙坦钠'
        ],
        // 急救常用
        firstaid: [
          '硝酸甘油',
          '西地兰针',
          '甘露醇',
          '生理盐水',
          '5%葡萄糖',
          '氯化钠注射液',
          '洛贝林',
          '盐酸异丙嗪',
          '尼可刹米',
          '阿托品',
          '肾上腺素',
          '呋塞米',
          '异丙肾上腺素',
          '地塞米松磷酸钠',
          '间羟胺',
          '多巴胺',
          '盐酸胺碘酮注射液',
          '甲磺酸粉妥拉明针'
        ],
        /* 他汀类（调脂药物）*/
        statins: [
          '阿托伐他汀',
          '瑞舒伐他汀',
          '洛伐他汀',
          '普伐他汀',
          '辛伐他汀',
          '氟伐他汀',
          '匹伐他汀',
          '依洛尤单抗',
          '依折麦布',
          '阿利西尤单抗'
        ], // 他汀类（调脂药物）
        /* 抗凝药*/
        anticoagulant: ['普通肝素', '低分子肝素', '比伐卢定', '黄达肝葵钠'],
        /* β受体阻滞剂*/
        retardant: [
          '酒石酸美托洛尔',
          '琥珀酸美托洛尔',
          '比索洛尔',
          '阿替洛尔',
          '普萘洛尔',
          '奈必洛尔',
          '卡维地洛'
        ]
      },
      drugArrList: [], // 药物复选框选中数组
      drugHistoryTime: {
        '阿司匹林': {
          meTime: '',
          creatTime: ''
        },
        '氯吡格雷': {
          meTime: '',
          creatTime: ''
        },
        '替格瑞洛': {
          meTime: '',
          creatTime: ''
        },
        '抗凝药': {
          meTime: '',
          creatTime: ''
        }
      }
    }
  },
  mounted() {
    this.getLifeDrug()
  },
  methods: {
    func(unit) {
      const arr = ['mg', 'ml', 'IU', '片']
      if (!arr.includes(unit) && unit !== undefined) {
        arr.unshift(...unit)
      }
      return Array.from(new Set(arr))
    },

    /* 新增生命支持 ------------------- */
    popupLife() {
      this.lifeChange = true
    },
    // 保存
    addSaveLife() {
      if (this.lifeTreatment && this.lifeTreatment.length === 0) {
        this.$message({
          message: `请选择生命支持具体选项`,
          type: 'warning'
        })
        return false
      }
      const lifeTreatment = this.lifeTreatment.join(',')
      const nowTime = format(new Date(), 'YYYY-MM-DD HH:mm:ss')
      const lifeData = {
        medicalid: this.checkrowdata.medicalId,
        dispatchId: this.checkrowdata.dispatchId,
        department: this.checkrowdata.departmentName,
        notes: this.lifeRemarks,
        time: nowTime,
        userId: this.checkrowdata.userId,
        id: null,
        treatment: JSON.stringify(this.lifeTreatment)
      }
      saveOtherTreatments(lifeData)
        .then((res) => {
          if (res.code === 0) {
            this.$message({
              message: '保存成功',
              type: 'success'
            })
            this.lifeChange = false
            this.lifeClearAll()
            this.getLifeDrug()
          } else {
            this.$message({
              message: '保存失败',
              type: 'error'
            })
          }
        })
        .catch(() => {
          this.$message({
            message: '保存失败',
            type: 'error'
          })
        })
    },
    lifeClearAll() {
      this.lifeTreatment = []
      this.lifeRemarks = ''
    },
    /* end --------------------------- */
    /* 新增药物 ------------------------*/
    /* 点击button */
    popup() {
      this.rapidDispensingChange = true
      this.clearAll()
    },
    addDeleteList(medicine, index, type) {
      // 根据点击多选增减下方药物列表
      /* 发生change事件运行至此,已完成对数组checkList的增减, 在此相应对saveList做出增减*/
      const arrIndex = this.addModelData.checkList.indexOf(medicine)
      if (arrIndex === -1) {
        // 若不存在,说明该药物被取消选中
        this.DeleteDrugName(medicine) // 根据药名删除药品
      } else {
        // 若存在,说明该药物被选中
        this.addToDrugName(medicine, type) // 故根据药名向saveList添加药品
      }
    },
    addToDrugName(name, type) {
      // 根据药名向saveList添加药品
      const YY = new Date().getFullYear()
      let MM = new Date().getMonth() + 1
      MM = MM < 10 ? '0' + MM : MM
      let DD = new Date().getDate()
      DD = DD < 10 ? '0' + DD : DD
      let hh = new Date().getHours()
      hh = hh < 10 ? '0' + hh : hh
      let mm = new Date().getMinutes()
      mm = mm < 10 ? '0' + mm : mm
      let ss = new Date().getDate()
      ss = ss < 10 ? '0' + ss : ss
      const time = YY + '-' + MM + '-' + DD + ' ' + hh + ':' + mm + ':' + ss
      const _data = this.drugList.filter(
        (item) => item['medicineType'] === type && item['medicineName'] === name
      )
      const medicineUnit = []
      _data.forEach((item) => {
        medicineUnit.push(item.medicineUnit)
      })
      this.saveList.push({
        itemName: type,
        medicineName: name,
        dosage: '',
        unit: _data[0].medicineUnit,
        // medicineTime :time
        medicineUnit: medicineUnit
      })
    },
    DeleteDrugName(name) {
      // 根据药名删除药品
      let arrIndex = ''
      this.saveList.forEach((el, index) => {
        if (el.medicineName === name) {
          arrIndex = index
          return
        }
      })
      if (arrIndex !== '') {
        /* 注意这里 ( 0!="") ->false      */
        this.saveList.splice(arrIndex, 1)
      }
    },
    saveData() {
      for (const el in this.saveList) {
        if (this.saveList[el].dosage === '') {
          const emptyCheck = this.saveList[el].medicineName
          this.$message({
            message: `药物 ${emptyCheck} 剂量不能为空`,
            type: 'warning'
          })
          return false
        }
        if (this.saveList[el].unit === '') {
          const emptyCheck = this.saveList[el].medicineName
          this.$message({
            message: `药物 ${emptyCheck} 单位不能为空`,
            type: 'warning'
          })
          return false
        }
      }
      const nowTime = format(new Date(), 'YYYY-MM-DD HH:mm:ss')
      console.log(nowTime, 'nowTime')
      for (const i in this.saveList) {
        this.saveList[i].medicineTime = nowTime
        this.saveList[i].medicineUnit = undefined
      }
      const newJson = {
        orderDetail: []
      }
      newJson.orderDetail = this.saveList
      const data = {
        userId: this.checkrowdata.userId,
        missionId: this.checkrowdata.dispatchId,
        medicalId: this.checkrowdata.medicalId,
        instanceType: 'medicine',
        json: JSON.stringify(newJson),
        status: 1,
        notes: this.remarks,
        polarity: 0,
        version: 0,
        judgement: 0,
        module: '药物',
        doctor: this.checkrowdata.doctorName,
        department: this.checkrowdata.departmentName
        // id : null
      }
      saveOtherMedicineg(qs.stringify(data))
        .then((res) => {
          if (res.code === 0) {
            this.$message({
              message: '保存成功',
              type: 'success'
            })
            this.rapidDispensingChange = false
            this.clearAll()
            this.getLifeDrug()
          } else {
            this.$message({
              message: res.error,
              type: 'error'
            })
          }
        })
        .catch(() => {
          this.$message({
            message: '保存失败',
            type: 'error'
          })
        })
    },

    delDrugIndex(index, drueName) {
      // 药品删除按钮(根据索引)
      this.saveList.splice(index, 1)
      const arrIndex = this.addModelData.checkList.indexOf(drueName)
      this.addModelData.checkList.splice(arrIndex, 1)
    },

    // 恢复默认值
    clearAll() {
      // 清除全部值
      this.addModelData.id = ''
      this.addModelData.tempName = ''
      this.addModelData.checkList = []
      this.addModelData.drugTemplate = []
      this.saveList = []
      this.remarks = ''
    },
    /* end ---------------------------------- */
    anticoagulatingSync(time, target) {
      this.medicineList[target].chipsOrder.json.orderDetail.map((item) => {
        if (item.itemName === '抗凝药') {
          item.medicineTime = time
        }
      })
    },
    historyTips(createdAt) {
      this.$message.info('请在 ' + createdAt + ' 的历史记录中修改时间')
    },
    addDelList(medicine, index) {
      // 根据点击多选增减下方药物列表
      /* 发生change事件运行至此,已完成对数组checkList的增减, 在此相应对orderDetail做出增减*/
      let medicineListIndex
      for (medicineListIndex in this.medicineList) {
        if (medicineListIndex === this.Subscript.toString()) {
          const arrIndex = this.modelData.checkList.indexOf(medicine)
          if (arrIndex === -1) {
            // 若不存在,说明该药物被取消选中
            this.delDrugName(medicine, index) // 根据药名删除药品
          } else {
            // 若存在,说明该药物被选中
            this.addDrugName(medicine, index) // 故根据药名向orderDetail添加药品
          }
        }
      }
    },
    /*
     *target 数据每一项的下标
     *index 药名每一项的下标
     */
    delDrugName(name, ind) {
      // 根据药名删除药品
      let medicineListIndex
      for (medicineListIndex in this.medicineList) {
        if (medicineListIndex === this.Subscript.toString()) {
          let arrIndex = ''
          this.medicineList[this.Subscript].chipsOrder.json.orderDetail.forEach(
            (el, index) => {
              if (el.medicineName === name) {
                arrIndex = index
                return
              }
            }
          )
          if (arrIndex !== '') {
            /* 注意这里 ( 0!="") ->false      */
            this.medicineList[
              this.Subscript
            ].chipsOrder.json.orderDetail.splice(arrIndex, 1)
          }
          this.medicineList[this.Subscript].drugArr.splice(name, 1)
        }
      }
    },
    // 药品类去重
    addNoRepetitionDrug(item) {

      this.addModelData.drugTemplate = Array.from(new Set(item))
      console.log("item",item, this.addModelData.drugTemplate)
    },

    addDrugName(name, index) {
      // 根据药名向saveList添加药品
      let type = ''
      if (this.medicineType === '胸痛') {
        type = this.chestPain.dapt.indexOf(name) > -1 ? '抗血小板药' : type
        type = this.chestPain.firstaid.indexOf(name) > -1 ? '急救常用' : type
        type = this.chestPain.aceiorarb.indexOf(name) > -1 ? 'ACEI/ARB' : type
        type = this.chestPain.statins.indexOf(name) > -1 ? '调脂药' : type
        type =
          this.chestPain.anticoagulant.indexOf(name) > -1 ? '抗凝药' : type
        type =
          this.chestPain.retardant.indexOf(name) > -1 ? 'β受体阻滞剂' : type
      } else {
        return
      }
      let medicineListIndex
      for (medicineListIndex in this.medicineList) {
        if (medicineListIndex === this.Subscript.toString()) {
          this.medicineList[this.Subscript].drugArr.push(name)
          this.medicineList[this.Subscript].chipsOrder.json.orderDetail.push({
            dosage: '',
            itemName: type,
            medicineName: name,
            unit: 'mg'
          })
        }
      }
    },
    handleLifeText(value) {
      this.lifeText = value
      this.saveLifeData.notes = value
    },
    // 生命支持保存
    lifeTreatments(val) {
      for (let j = val; j < val + 1; j++) {
        if (val === j) {
          this.saveLifeData.notes = this.treatmentList[val].notes
          this.saveLifeData.user = this.treatmentList[val].userId
          this.saveLifeData.id = this.treatmentList[val].id
          this.saveLifeData.time = this.treatmentList[val].time
          this.saveLifeData.treatment = JSON.stringify(
            this.treatmentList[val].treatment
          )
          const saveLifeData = this.saveLifeData
          saveOtherTreatments(saveLifeData)
            .then((res) => {
              if (res.code == 0) {
                this.$message({
                  message: '保存成功',
                  type: 'success'
                })
              } else {
                this.$message({
                  message: res.error,
                  type: 'error'
                })
              }
            })
            .catch(() => {
              this.$message({
                message: '保存失败',
                type: 'error'
              })
            })
        } else {
          return
        }
      }
    },
    // 药物备注
    handleDrugText(value) {
      this.lifeText = value
      this.saveMedicineData.notes = value
    },
    // 药物种类确定
    // 药物保存
    saveMedicine(val) {
      const reportTime = format(new Date(), 'YYYY-MM-DD HH:mm:ss')
      for (let j = val; j < val + 1; j++) {
        if (val === j) {
          const orderDetail = {
            orderDetail: this.medicineList[val].orderDetailArr
          }
          console.log(this.medicineList[val].chipsOrder.json, 'josn')
          this.saveMedicineData.userId = this.medicineList[val].chipsOrder.userId
          this.saveMedicineData.missionId = this.medicineList[val].chipsOrder.missionId
          this.saveMedicineData.medicalId = this.medicineList[val].chipsOrder.medicalId
          this.saveMedicineData.instanceType = this.medicineList[val].chipsOrder.instanceType
          this.saveMedicineData.json = JSON.stringify(orderDetail)
          this.saveMedicineData.status = this.medicineList[val].chipsOrder.status
          this.saveMedicineData.notes = this.medicineList[val].chipsOrder.notes
          this.saveMedicineData.polarity = this.medicineList[val].chipsOrder.polarity
          this.saveMedicineData.version = this.medicineList[val].chipsOrder.version
          this.saveMedicineData.judgement = this.medicineList[val].chipsOrder.judgement
          this.saveMedicineData.module = this.medicineList[val].chipsOrder.module
          this.saveMedicineData.doctor = this.medicineList[val].chipsOrder.doctor
          this.saveMedicineData.department = this.medicineList[val].chipsOrder.department
          this.saveMedicineData.id = this.medicineList[val].chipsOrder.id
          this.saveMedicineData.time = this.medicineList[val].time
          const saveMedicineData = this.saveMedicineData
          // saveOtherMedicineg(qs.stringify(saveMedicineData))
          saveOtherMedicineg(qs.stringify(saveMedicineData))
            .then((res) => {
              this.$message({
                message: '保存成功',
                type: 'success'
              })
              this.getLifeDrug()
            })
            .catch(() => {
              this.$message({
                message: '保存失败',
                type: 'error'
              })
            })
        } else {
          return
        }
      }
    },
    // 获取数据---------------
    getLifeDrug() {
      // { dispatchId: 103148 }
      const DrugInformationData = {
        pageNum: '',
        pageSize: '',
        greenType: '胸痛',
        medicineType: '',
        apiToken: this.$store.getters.apiToken
      }
      /* 获取药物信息 -> 生成列表 */
      selectList(DrugInformationData)
        .then((res) => {
          if (res.code === 0) {
            this.drugList = res.data.list
            // console.log(res.data.list)
            const drugObj = {}
            res.data.list.forEach((item) => {
              const array = drugObj[item['medicineType']] || []
              array.push(item.medicineName)
              drugObj[item['medicineType']] = array
            })
            this.drugType = drugObj
            console.log(this.drugType)
          }
        })
        .catch((err) => {
          this.$message.error(err)
        })
      // this.drugType = {}
      // this.drugType["抗血小板药物"] = JSON.parse(JSON.stringify(this.chestPain.dapt))
      this.dispatchIdInFo.dispatchId = this.checkrowdata.dispatchId
      const data = this.dispatchIdInFo
      queryListDisGet(data)
        .then((res) => {
          this.treatmentList = []
          this.medicineList = []
          this.drugArrList = []
          const dataArr = res.data
          for (let i = 0; i < dataArr.length; i++) {
            if (dataArr[i].datatype === 'treatment') {
              this.treatmentList.push(dataArr[i])
            } else if (dataArr[i].datatype === 'medicine') {
              for (let j = 0; j < JSON.parse(dataArr[i].chipsOrder.json).orderDetail.length; j++) {
                let arr = []
                const item = JSON.parse(dataArr[i].chipsOrder.json).orderDetail[j]
                if (this.drugHistoryTime[item.medicineName] !== undefined) {
                  this.drugHistoryTime[item.medicineName].meTime = item.medicineTime || dataArr[i].time
                  this.drugHistoryTime[item.medicineName].creatTime = dataArr[i].time
                  // this.drugHistoryTime[item.medicineName] = {
                  //   meTime: item.medicineTime || dataArr[i].time,
                  //   creatTime: dataArr[i].time
                  // }
                }
                if (this.drugHistoryTime[item.itemName] !== undefined) {
                  this.drugHistoryTime[item.itemName] = {
                    meTime: item.medicineTime || dataArr[i].time,
                    creatTime: dataArr[i].time
                  }
                }
                arr = JSON.parse(dataArr[i].chipsOrder.json).orderDetail.map((item) => {
                  return item.medicineName
                })
                dataArr[i].drugArr = arr
                dataArr[i].orderDetailArr = JSON.parse(dataArr[i].chipsOrder.json).orderDetail
              }
              this.medicineList.push(dataArr[i])
              this.drugArrList.push(dataArr[i].drugArr)
            } else {
              return
            }
          }
          // 生命支持-复选框
          for (let j = 0; j < this.treatmentList.length; j++) {
            var str = this.treatmentList[j].treatment
            var arr = eval('( ' + str + ' )')
            this.treatmentList[j].treatment = arr
            // this.saveLifeData.treatment = JSON.stringify(this.treatmentList[j].treatment)
          }
        })
        .catch((err) => {
          this.$message.error(err)
        })
    },
    deleteData(value, type) {
      const formData = new FormData()
      // console.log(value)
      if (type === 1) {
        // console.log(value)
        formData.append("id", value.chipsOrder.id)
        formData.append("dispatchId", "0")
        formData.append("type", value.chipsOrder.instanceType)
        formData.append("apiToken", this.$store.getters.apiToken)
        // return
      } else if (type === 2) {
        formData.append("id", value.id)
        formData.append("dispatchId", value.dispatchId)
        formData.append("type", value.datatype)
        formData.append("apiToken", this.$store.getters.apiToken)

      }
      deleteOtherTreatments(formData)
          .then((res) => {
            if (res.code == 0) {
              this.$message({
                message: '删除成功',
                type: 'success'
              })
              this.getLifeDrug()
            } else {
              this.$message({
                message: res.error,
                type: 'error'
              })
            }
          })
          .catch(() => {
            this.$message({
              message: '删除失败',
              type: 'error'
            })
          })
    }
  }
}
</script>

<style scoped>
/* 边框*/
.disposal {
  width: 100%;
  padding: 20px 40px;
}

/* 其他处置text */
.text-other {
  color: #3997fb;
  margin: -40px 0 10px -10px;
  font-size: 18px;
}

/*生命支持*/
.lifeSupport {
  background-color: #f2f2f2;
  width: 100%;
  margin-top: 5px;
  padding: 10px 20px;
}

.text-life {
  font-size: 16px;
  font-weight: 600;
  margin-left: -10px;
}

/* 生命支持内部*/
.line {
  display: block;
  width: 100%;
  height: 1px;
  background-color: #949494;
  position: absolute;
  bottom: -15px;
}

.life-box {
  margin: 10px 0 30px 0px;
  font-size: 14px;
  width: 100%;
  position: relative;
}

.life-lift {
  /* margin: 30px 0 0px 0; */
  margin: 20px 0 0px 0;
  float: left;
  width: 70%;
}

.life-right {
  /* margin: 35px 10px 0px 0; */
  float: right;
  color: #4d4d4d;
}

.jizhen-text {
  margin: 0 20px;
}

/* 中间药物选择 */
.life-center {
  clear: both;
  margin-bottom: 10px;
  width: 100%;
  background-color: #e4e4e4;
}

.item {
  padding: 5px 30px;
}

/* --------- end -------------*/
.life-bottom {
  clear: both;
  padding-top: 10px;
}

.life-many {
  font-size: 18px;
  padding-top: 10px;
}

.beizhutext {
  float: left;
  margin-right: 10px;
  margin-top: 10px;
}

/* 药物*/
.drug {
  background-color: #f2f2f2;
  width: 100%;
  margin-top: 5px;
  padding: 10px 20px;
}

/* 新增  */
.addContent {
  width: 100%;
  height: 50px;
  border-bottom: 1px solid #dfdee3;
}

.dialogStyle {
  text-align: center;
  min-width: 700px;
  /* min-height: 400px; */
}
</style>
